<?php
namespace Home\Controller;
use Home\Controller\BaseController;
class ReporterController extends BaseController {


    /**
     * 用户列表
     */
    public function index(){


        if(!session('is_admin') && !session('is_type'))
            $this->redirect('Article/index');

        
        $userName = I('get.username', '', 'trim');
        $mobile = I('get.mobile', '');
        $p=16;
        $pagenum=I('get.p',0);
        $map = array();
        if($userName) {
            $map['realname'] = array("like","%{$userName}%");
        }
        if($mobile) {
            $map['mobile'] = $mobile;
        }

        $userchannel=M('channel')->where(array('org_id'=>$this->adminInfo['organ']))->select();

        if($userchannel){
            $arr=array();
//            foreach($userchannel as $v){
//                $arr[]=$v['chid'];
//            }

//            $map['userchannel'] = array('in',$arr);

            $map['userchannel'] = array('in',$this->channelId);
//            $map['ui.status'] = 1;

            $userModel = M('User');
            $total = $userModel
                ->alias('u')->join('__USER_INFO__ ui ON u.uid = ui.uid')
                ->where($map)
                ->count();

            $page = new \Think\Page($total, $p);
            $show = $page->show();

            $userList = $userModel->alias('u')
                ->field('*,ui.status userstatus,jb.name jobsname,ch.name channelname,ui.realnamepy realnamepy')
                ->join('__USER_INFO__ ui ON u.uid = ui.uid')
                ->join('__JOB__ jb on jb.jid=ui.userjobs','left')
                ->join('__CHANNEL__ ch on ch.chid=ui.userchannel','left')
                ->where($map)
                ->page($pagenum.','.$p)
                ->order('u.uid DESC')
                ->select();
        }else{
            $userList =array();
        }

        $this->assign('page', $show);
        $this->assign('active', '账户管理');
        $this->assign('userList', $userList);
        $this->display();
    }



    public function ajaxdeluer($uid=''){
        $user_info=M('User_info');
        $user=M('User');
        $frontUser=M('FrontUser');
        if($uid){

            $user_info->startTrans();
//            if($user_info->where(array('uid'=>$uid))->delete() && $user->delete($uid) && $frontUser->where(array('reporter_id'=>$uid))->save(array('reporter_id'=>0))){
            if($user_info->where(array('uid'=>$uid))->save(array('status' => 0)) && $frontUser->where(array('reporter_id'=>$uid))->save(array('reporter_id'=>0))) {
                $user_info->commit();
                $this->ajaxReturn(1);
            }else{
                $user_info->rollback();
                $this->ajaxReturn(0);
            }
        }else{
            return false;
        }
    }

    public function ajaxdeluerall($uid=''){
        $user_info=M('User_info');
        $user=M('User');
        $frontUser=M('FrontUser');
        if($uid){
            $user_info->startTrans();
 
//            if($user_info->where("uid in ($uid)")->delete() && $user->where("uid in ($uid)")->delete()  && $frontUser->where(array('reporter_id'=>$uid))->save(array('reporter_id'=>0))){

            if($user_info->where("uid in ($uid)")->save(array('status' => 0)) && $frontUser->where(array('reporter_id'=>$uid))->save(array('reporter_id'=>0))) {
                $user_info->commit();
                $this->ajaxReturn(1);
            }else{
                $user_info->rollback();
                $this->ajaxReturn(0);
            }
        }else{
            return false;
        }
    }

    public function ajaxgetuserinfo($uid=''){
        $user=M('User');
        if($uid){
            $userinfo=$user->alias('u')->join('__USER_INFO__ on __USER_INFO__.uid=u.uid')->where('u.uid='.$uid)->find();
            if($userinfo){
                $this->ajaxReturn($userinfo);
            }else{
                $this->ajaxReturn(0);
            }
        }else{
            return false;
        }
    }

    public function editUserAction(){
        C('TOKEN_ON',false);
        if(IS_POST){
            $user=D('user');
            $user_info=D('UserInfo');

            if(!$_POST['username']) {
                unset($_POST['username']);
            }

            if($user_info->create()){
                $res=$user_info->save();
                if($res){
                    M('FrontUser')->where(array('reporter_id'=>I('post.uid')))->save(array('mobile'=>I('post.mobile')));
                }
                if(I('post.password')){
                    if($user->create()) {
                        $user->save();
                        M('FrontUser')->where(array('reporter_id'=>I('post.uid')))->save(array('password'=>md5(C('PWD_SALT') . I('post.password'))));
                    } else {
                        $this->error($user->getError(),$_SERVER['HTTP_REFERER']);
                    }
                }
                $this->success('修改成功',U('index'));
            }else{
                if($user->getError()){
                    $this->error($user->getError(),$_SERVER['HTTP_REFERER']);
                }else{
                    $this->error($user_info->getError(),$_SERVER['HTTP_REFERER']);
                }
            }
        }
    }

    public function addUserAction(){
        if(IS_POST){
            if(!M('User')->create()){
                $this->error(M('User')->getError());
            }


            if(!I('post.password')){
                $_POST['password']='123456';
            }

            if(!(I('post.realname')&&I('post.mobile')&&I('post.userchannel')&&I('post.idcard')&&I('post.validimg'))){
                $this->error('参数错误！');
            }

            $mess=$this->validateIdCard_f(I('post.idcard'));
            if($mess['status']=='n'){
                $this->error($mess['info']);
            }

            $_POST['username']='m'.time();
            $_POST['password']=md5(C('PWD_SALT').I('post.password'));;
            M()->startTrans();
            $res=M('User')->add(array('username'=>I('post.username'),'password'=>I('post.password'),'createtime'=>time()));
            if($res){
                $dataGet['uid']=$res;
                $dataGet['realname']=I('post.realname');
                $dataGet['mobile']=I('post.mobile');
                $dataGet['userchannel']=I('post.userchannel');
                $dataGet['idcard']=I('post.idcard');
                $dataGet['realnamepy']=zh2py(I('post.realname'));
                $dataGet['validimg']="/Uploads/".I('post.validimg');
                $dataGet['userorg'] = $this->adminInfo['organ']; // 机构
                $res2=M('UserInfo')->add($dataGet);
                if($res2){
                    $front_res=M('FrontUser')->getByMobile($dataGet['mobile']);
                    if($front_res){
                        $res3=M('FrontUser')->where(array('mobile'=>$dataGet['mobile']))->save(array('reporter_id'=>$res));
                        if(!$res3){
                            M()->rollback();
                            $this->error('添加用户失败');
                        }
                    }else{
                        $dataGet2['username']='jw'.time();
                        $dataGet2['password']=I('post.password');
                        $dataGet2['mobile']=$dataGet['mobile'];
                        $dataGet2['reporter_id']=$res;
                        $dataGet2['nickname']=$dataGet['realname'];
                        $dataGet2['create_time']=time();
                        $res3=M('FrontUser')->add($dataGet2);
                        if(!$res3){
                            M()->rollback();
                            $this->error('添加用户失败',$_SERVER['HTTP_REFERER']);
                        }
                    }
                    M()->commit();
                    $this->success('添加用户成功',U('index'));

                }else{
                    M()->rollback();
                    $this->error('添加用户失败',$_SERVER['HTTP_REFERER']);
                }
            }else{
                M()->rollback();
                $this->error('添加用户失败',$_SERVER['HTTP_REFERER']);
            }
        }

    }

    public function ajaxcheckusername(){
        $_POST['username']=$_POST['param'];
        if(I('get.uid')){
            $_POST['uid']=I('get.uid');
        }
        if(D('User')->create()){
            echo '{
            "info":" ",
            "status":"y"
            }';
        }else{
            echo '{
                "info":"'.D('User')->getError().'",
                "status":"n"
            }';
        }

    }
    public function ajaxMobileCheck(){
        C('TOKEN_ON',false);
        $_POST['mobile']=$_POST['param'];
        if(I('get.uid')){
            $_POST['uid']=I('get.uid');
        }
        if(D('UserInfo')->create()){
            echo '{
            "info":"此手机可以使用",
            "status":"y"
            }';
        }else{
            echo '{
                "info":"'.D('UserInfo')->getError().'",
                "status":"n"
            }';
        }

    }


    public function ajaxEmailCheck(){
        $_POST['email']=$_POST['param'];
        if(I('get.uid')){
            $_POST['uid']=I('get.uid');
        }
        if(D('UserInfo')->create()){
            echo '{
            "info":" ",
            "status":"y"
            }';
        }else{
            echo '{
                "info":"'.D('UserInfo')->getError().'",
                "status":"n"
            }';
        }

    }

    function authTree($authlist=""){
        $authlist=explode(",",$authlist);
        $system_channel_model=M('SystemChannel');
        $top_auth_list=$system_channel_model->where(array("spid"=>0,"ishide"=>1))->select();
        $arr['id']=0;
        $arr['item']=array();

        foreach($top_auth_list as $k=>$v){
            $arr['item'][]=array('id'=>"T_".$v['scid'],'child'=>'1','text'=>$v['channelname'],'item'=>array());
            $seconde_auth_list=$system_channel_model->where(array("spid"=>$v['scid'],"ishide"=>1))->select();
            foreach($seconde_auth_list as $kk=>$vv){
                $arr['item'][$k]['item'][$kk]=array('id'=>$vv['scid'],'text'=>$vv['channelname']);
                if(in_array($vv['scid'],$authlist)){
                    $arr['item'][$k]['item'][$kk]['checked']="1";
                }
            }
        }
        $this->ajaxReturn($arr);
    }

    function ajaxSetUserAuth(){
        $idList=I("get.idList");
        $regx='/^\d+$/';
        foreach(explode(",",$idList) as $v){
            preg_match($regx,$v,$a);
            if(count($a)>=1){
                $arr[]=$v;
            }
        }

        $idList=implode(",",$arr);

        $a=M('UserInfo')->save(array(
            'userauth'=>$idList,
            'uid'=>I("get.uid")
        ));
        $this->ajaxReturn($a);
    }


    function formatPinyinName(){
        ini_set('max_execution_time','0');
        $user=M('UserInfo')->where('realnamepy=""')->select();
        foreach($user as $v){
            M('userInfo')->where(array('uid'=>$v['uid']))->save(array('realnamepy'=>zh2py($v['realname'])));
            echo M()->_sql().'<br>';
        }

    }

    function formatPw(){
        $user=M('User')
            ->alias('u')
            ->join("__USER_INFO__ ui ON u.uid=ui.uid","left")
            ->select();
        foreach($user as $v){
            M('user')->where(array('uid'=>$v['uid']))->save(array('password'=>md5('whtvjw'.$v['mobile'])));
        }
    }

    public function setReporterStatus(){
        $uid=I('get.uid');
        if($uid && preg_match("/^\d+$/",$uid)){
            $status=M('UserInfo')->getFieldByUid($uid,'status');

            $status=(int) !$status;
            $res=M('UserInfo')->where(array('uid'=>$uid))->save(array('status'=>$status));
            $mess['status']=$res;
            $mess['info']=$status;

            $this->ajaxReturn($mess);
        }
    }

    public function addReporter(){
//        $res=M('Channel')->where(array('org_id'=>$this->adminInfo['organ'],'status'=>1))->select();
        $res=M('Channel')->where(array('chid'=>array('in', $this->channelId),'status'=>1))->select();
        $this->assign('active', '账户管理');
        $this->assign('channel_list', $res);
        $this->display();
    }

    public function editReporter(){
        $uid=I('get.uid');
        if($uid){
            $reporter=M('user_info')->find($uid);
            $department=M('Channel')->getFieldByChid($reporter['userchannel'],'name');
            $res=M('Channel')->where(array('chid'=>array('in', $this->channelId),'status'=>1))->select();
            $reporter['department']=$department;
            $this->assign('active', '账户管理');
            $this->assign('reporter', $reporter);
            $this->assign('channel_list', $res);
            $this->display();
        }else{
            $this->error('参数错误！');
        }

    }

    private function validateIdCard_f($idCard,$uid=null){
        
        
        if($idCard){
            //15位和18位身份证号码的正则表达式
            $regIdCard='/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/';

            if(preg_match($regIdCard,$idCard)){ 

                $a=str_split($idCard,1);
                $w=array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);

                $c=array(1,0,'X',9,8,7,6,5,4,3,2);


                $sum=0;
                for($i=0;$i<17;$i++){
                    $sum=$sum+$a[$i]*$w[$i];
                }

                $r=$sum%11;
                $res=$c[$r];

                if($res==strtoupper($a[17])){
                    $map['idcard']=$idCard;
                    if($uid){
                        $map['uid']=array('neq',$uid);
                    }
                    $res=M('UserInfo')->where($map)->find();
                    if($res){
                        $mess['status']='n';
                        $mess['info']="身份证已经注册";
                    }else{
                        $mess['status']='y';
                        $mess['info']="通过验证";
                    }
                }else{
                     $mess['status']='n';
                    $mess['info']="身份证号码错误";
                    
                }
                return $mess;
            }else{
                $mess['status']='n';
                    $mess['info']="身份证号码错误";
                    return $mess;
            }
        }else{
            $mess['status']='n';
            $mess['info']="身份证号码错误";
            return $mess;
        }
    }

    public function validateIdCard(){
    	$idCard=I('post.param');
    	$uid=I('get.uid');
        $this->ajaxReturn($this->validateIdCard_f($idCard,$uidss));
    }

    public function checkFrontUser(){
        $mobile=I("get.mobile");
        $reporter_id=I("get.reporter_id");

        if($mobile){
            $front_res=M('FrontUser')->getByMobile($mobile);
            if($front_res['reporter_id']!=$reporter_id){
                echo 1;
            }else{
                echo 0;
            }
        }else{
            echo -1;
        }
    }

    public function validImg(){
        $upload = new \Think\Upload();
        $upload->rootPath  =    '/var/www/local.www.jianweitv.com/Uploads/';
        $upload->maxSize   =     3145728 ;
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');
        $upload->savePath  =      'validImg/'; // 设置附件上传目录
        $upload->saveName  =      time().'_'.mt_rand();
        $upload->subName   =      array('date','Y/m/d');
        $upload->autosub   =      true;

        $info   =   $upload->upload();
        if(!$info) {
            $mess['resultCode']=1;
            $mess['info']=$upload->getError();
        }else{
            $mess['resultCode']=0;
            $mess['info']=$info['file']['savepath'].$info['file']['savename'];
        }

        $this->ajaxReturn($mess);
    }
}